﻿using AutoMapper;
using B.S.BaseData.Domain.Entities;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Infrastructure.Interfaces;
using B.S.BaseData.Read.API.Command.RoleCommand;
using B.S.BaseData.Read.API.DTO;
using MediatR;

namespace B.S.BaseData.Read.API.CommandHandler.RoleHandler
{
    public class QueryRoleUserHandler : IRequestHandler<QueryRoleUserCommand, APIResult<List<RUDTO>>>
    {
        private readonly IBaseRepository<User> userRep;
        private readonly IBaseRepository<Role> roleRep;
        private readonly IBaseRepository<UserRole> urRep;
        private readonly IMapper mapper;

        public QueryRoleUserHandler(IBaseRepository<User> userRep,IBaseRepository<Role> roleRep,IBaseRepository<UserRole> urRep,IMapper mapper)
        {
            this.userRep = userRep;
            this.roleRep = roleRep;
            this.urRep = urRep;
            this.mapper = mapper;
        }
        public Task<APIResult<List<RUDTO>>> Handle(QueryRoleUserCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<RUDTO>> result=new APIResult<List<RUDTO>>();
            var list = from a in userRep.GetAll()
                       join b in urRep.GetAll() on a.UserId equals b.UserId
                       join c in roleRep.GetAll() on b.RoleId equals c.RoleId
                       where b.RoleId == request.RoleId
                       select new RUDTO
                       {

                           UserId = a.UserId,
                           Name = a.Name,
                           RoleId = b.RoleId,
                           RoleName = c.RoleName,
                           URId = b.URId,
                       };
            result.Code=APIEnum.Success;
            result.Msg = "查询成功";
            result.Data = mapper.Map<List<RUDTO>>(list);
            return Task.FromResult(result);
        }
    }
}
